$(function () {
    initCate()

    function initCate() {
        let layer = layui.layer
        let form = layui.form
        $.ajax({
            method: 'GET',
            url: '/my/article/cates',
            success: res => {
                if (res.status !== 0) {
                    return layer.msg('初始化文章分类失败!')
                }
                // 调用模板引擎
                let htmlStr = template('tpl-cate', res)
                $('[name=cate_id]').html(htmlStr)
                form.render()
            }
        })
    }

    // 初始化富文本编辑器
    initEditor()

    // 1. 获取图片
    var $image = $('#image')

    // 2. 裁剪选项
    var options = {
        aspectRatio: 400 / 280,
        preview: '.img-preview'
    }

    // 3. 初始化裁剪区域
    $image.cropper(options)

    $('#btnChooseImage').on('click', function () {
        $('#coverFile').click()
    })

    $('#file').on('change', function (e) {
        let fileList = this.files
        if (fileList.length <= 0) {
            return layui.layer.msg('请选择图片')
        }
        //  将文件，转化为路径
        let imgURL = URL.createObjectURL(fileList[0])
        //  重新初始化裁剪区域
        $image
            .cropper('destroy')
            .attr('src', imgURL)
            .cropper(options)
    })


    
    let art_state = '已发布'
    $('#btnSave').on('click', function () {
        art_state = '草稿'
    })

    $('#form').on('submit', function (e) {
        e.preventDefault()
        const fd = new FormData(this)
        fd.append('state', art_state)
    })

    $image
        .cropper('getCroppedCanvas', {
            width: 400,
            height: 280
        })
        .toBlob(function (blob) {
            fd.append('cover_img', blob)
            $.ajax({
                method: 'POST',
                url: '/my/article/add',
                data: fd,
                contentType: false,
                processData: false,
                success: res => {
                    const {
                        status,
                        message
                    } = res
                    if (status !== 0) {
                        return layui.layer.msg(message)
                    }
                    layui.layer.msg('文章发表成功')
                    location.href = '/artcate/art_list.html'
                    window.parent.document.querySelector('#list').click()
                }
            })
        })
})